<?php
namespace Modules\Activity\Http\Controllers\Client\Fudai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Fudai\Activity;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;
use Setting;

// 福袋活动
class ActivityController extends Controller
{
    // 首页获取配置
    public function homeConfig(Request $req)
    {
        $setting = @Setting::get('sys_fudai_base') ?: [];
        $setting['ui'] = Setting::get('ui_fudai_home');

        return [
            'setting' => $setting
        ];
    }

    // 首页列表
    public function homeIndex(Request $req)
    {
        $options = $req->all();
        $options['per_page'] = 20;
        $options['scopes'] = ['onStock'];
        $options['order_by'] = ['list_weight' => 'desc'];
        $options['with'] = ['skus'];

        $header_arr = explode('-', $req->header('Client-Type'));
        $platformType = @$header_arr[0];
        $clientType = @$header_arr[2];

        if ( $platformType == 'app' && $clientType == 'app' ){
//            $options['where'][] = ['title', 'like', 'APP_%'];
        }else{
            $options['where'][] = ['title', 'not like', 'APP_%'];
        }


        $setting = @Setting::get('ui_fudai_home') ?: [];

        // \Log::error($setting);
        if (@$setting['list_type'] === 'custom') {
        	// \Log::error(@$setting['home_fudais']);
        	$options['ids'] = @$setting['home_fudais'] ?: [];
        }

        $options['only'] = [
            'id',
            'uuid',
            'money_price',
            'score_price',
            'title',
            'sub_title',
            'thumb',
            'activity_type_text',
            'activity_type',
            'total_list',
            'image_3d',
            'skus' => [
                '*' => [
                    'id',
                    // 'uuid',
                    'thumb',
                    // 'title',
                    // 'number',
                    // 'level'
                ]
            ]
        ];

        $list = Activity::getList($options);

        $list->each(function($item) {
            $item->total_list = $item->calcTotalList();
        });

        return $list->generateListResponse();
    }

    // 常规列表
    public function index(Request $req)
    {
        $options = $req->all();
        // $options['per_page'] = 200;
        $options['scopes'] = ['onStock'];
        $options['order_by'] = ['list_weight' => 'desc'];
        // $options['with'] = ['skus'];

        $header_arr = explode('-', $req->header('Client-Type'));
        $platformType = @$header_arr[0];
        $clientType = @$header_arr[2];

        if ( $platformType == 'app' && $clientType == 'app' ){
//            $options['where'][] = ['title', 'like', 'APP_%'];
        }else{
            $options['where'][] = ['title', 'not like', 'APP_%'];
        }

        $options['only'] = [
            'id',
            'uuid',
            'money_price',
            'score_price',
            'tags',
            'sales',
            'title',
            'sub_title',
            'thumb',
            'activity_type_text',
            'activity_type',
        ];

        $list = Activity::getList($options);

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid) 
    {
        $activity = Activity::getEntity([
            'uuid' => $uuid,
            // 'with' => ['skus']
        ]);

        $only  = [
            'id',
            'uuid',
            'title',
            'thumb',
            'images',
            'detail_images',
            'money_price',
            'score_price',
            'image_3d',
            'is_invite_enabled',
            'is_share_enabled',
            'invite_rule',
            'level_total',
            'sku_level' => [
                '*' => [
                    'odds',
                    'title',
                    'icon',
                    'level'
                ]
            ],
            'skus' => [
                '*' => [
                    'id',
                    'uuid',
                    'title',
                    'thumb',
                    'number',
                    'odds',
                    'level',
                    'stock',
                    'detail_images',
                    'product_id',
                    'money_price',
                    'score_price',
                    'cover_score_price'
                ]
            ]
        ];

        // 所有展示出来的sku
        $activity->skus  = $activity->getDisplaySkus()->each(function ($item) {
            $item->money_price = $item->display_money_price;
            $item->score_price = $item->display_score_price;
            $item->odds = $item->total_odds;
        })->toArray();

        // sku_level 进行全局替换
        $globalSetting = @Setting::get('sys_fudai_sku_level')['list'];
        if ($globalSetting) {
            $currentSetting = $activity->sku_level;
            $currentSetting = $activity->getAllSkuLevel();

            foreach ($currentSetting as $key => $item) {
                $currentSetting[$key]['title'] = @$item['title'] ?: @$globalSetting[$key]['title'];
                $currentSetting[$key]['icon'] = @$item['icon'] ?: @$globalSetting[$key]['icon'];
                $currentSetting[$key]['level'] = $key + 1;
            }

            $activity->sku_level = array_values(array_filter($currentSetting, function ($item) {
                return @$item['status'] == 1;
            }));

            $activity->level_total = count($activity->sku_level);
        }

        $info = $activity->getInfo($only);

        // 计算连开几个的列表
        $info['total_list'] = $activity->calcTotalList();

        $setting = @Setting::get('sys_fudai_base') ?: [];

        $config = [
            'animation_mode' => @$setting['animation_mode'] ?: 'theme1',   // 默认是开盒动画1
            'show_odds_mode' => @$setting['show_odds_mode'] ?: 'enable',
            'is_show_rank' => @Setting::get('sys_fudai_record_list')['is_show'] ? 1 : 0
        ];

        return [
            'info' => $info,
            'config' => $config
        ];
    }

    // 切换福袋
    public function change(Request $req)
    {
        $rule = [
            'fudai_id' => ['required'],  // 要切换到的福袋id
            // 'room_id'
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $activity = Activity::getEntity([
            'id' => $req->fudai_id,
            'with' => ['skus']
        ]);

        if ($activity->stock === 0) {
            ThrowException::Conflict('此款已售罄~');
        }

        // $sku = $activity->pickLuckySku(null, null, [
        //     'add_sales' => false   // 不扣库存
        // ]);

        // 如果基础款的库存为0，则直接下架
        $sku = $activity->skus()->where('level', 1)->onStock()->where('stock', '>', 0)->first();

        if (!$sku) {
            ThrowException::Conflict('此款已售罄~');
        }

        // 页面pageUuid
        $pageUuid = uniqid();

        // 缓存里面的内容
        $cached = [
            'fudai_id' => $req->fudai_id,
            'sku_id' => $sku->id
        ];
        Cache::put($pageUuid, $cached, 1800);


        // $info = $activity->getInfo([
        //     'id',
        //     'uuid',
        //     'title',
        //     'money_price',
        //     'skus' => [
        //         '*' => [
        //             'id',
        //             'uuid',
        //             'thumb',
        //             'title',
        //             'number',
        //             'level'
        //         ]
        //     ]
        // ]);

        $info['page_uuid'] = $pageUuid;

        return $info;
    }
}
